/*! JRoll.Infinite v0.0.1 ~ (c) 2015
 *Author:jlong
 *Email:jlong@chjtx.com
 *Website:http://www.chjtx.com/JRoll/#todo/tutorial?do=infinite
 */
;(function(window, document) {
  "use strict";
  var sty = document.createElement('div').style;
  var tSF = ("transform" in sty) ? "transform" : "-webkit-transform";
  var tSD = ("transitionDuration" in sty) ? "transition-duration" : "-webkit-transition-duration";
  var normalImport = function(d){ //强制普通模式引入，script添加"jroll-import='normal'"属性后将忽略exports/define等方式引入
    var s = d.getElementsByTagName("script");
    for (var i=s.length-1; i>-1; i--) {
      if (s[i].getAttribute("jroll-import") === 'normal') {
        return true;
      }
    }
    return false;
  }(document);
  
  function gId(id) {
    return document.getElementById(id);
  }
  function qSr(selector) {
    return document.querySelector(selector);
  }
  function cDiv(tag) {
    return document.createElement(tag);
  }
  function randomIdPrefix() { //得到一个随机id前缀，为避免多次使用JRoll_Infinite产生相同的ID造成冲突
    var a = ["a","b","c","d","e","f","g","h","i","j"];
    var r = "", i=5;
    while (i--) {
      r += a[parseInt(Math.random()*10, 10)];
    }
    return r + "_";
  }
  //在head插入动画css
  (function(document){
    var style = cDiv("style");
    style.innerHTML = ".jroll-infinite-loading{-webkit-animation:jroll_infinite_loading 600ms linear infinite;animation:jroll_infinite_loading 600ms linear infinite}@-webkit-keyframes jroll_infinite_loading{from{-webkit-transform:rotateZ(0deg)}to{-webkit-transform:rotateZ(360deg)}}@keyframes jroll_infinite_loading{from{transform:rotateZ(0deg)}to{transform:rotateZ(360deg)}}";
    document.head.appendChild(style);
  })(document);

  function JRoll_Infinite(wrap, options, jOptions) {
    //检测是否已加载JRoll
    if (typeof JRoll === 'undefined') {
      console.error("必须先加载JRoll!");
      return;
    }
    var me = this;
    me.page = 1;
    me.refresh = false; //下拉刷新标记
    me.lock = false; //每次加载新页都会上锁，直到新页加载完成才开锁
    me.prefix = randomIdPrefix();
    me.direction = "+"; //滑动方向，默认向下，+表示向下 -表示向上
    me.options = {
      total: 10, //总页数
      limit: false, //限制最多只显示3页，默认不使用增减模式
      pullCss: "position:absolute;top:-42px;left:0;width:100%;height:42px;line-height:42px;text-align:center;",
      iconPull: "\u2193",
      iconUpdate: "\u21bb",
      iconCss: "display:inline-block;margin:0 5px;",
      textPull: "下拉刷新",
      textRelease: "释放刷新",
      textUpdate: "正在加载...",
      textCss: "",
      getData: null,  //获取数据的函数，必须返回一个数组，数组元素必须为对象
      template: "", //每条数据模板
      loadingTip: "<div class=\"jroll-infinite-tip\">正在加载...</div>",  //正在加载提示信息
      completeTip: "<div class=\"jroll-infinite-tip\">已加载全部内容</div>" //加载完成提示信息
    };

    for (var i in options) {
      me.options[i] = options[i];
    }
    
    if (typeof jOptions !== "object") {
      jOptions = {
        bounce : true,
        scrollX: false
      };
    }

    //用于清除提示信息
    me.clearRegExp = new RegExp("("+me.options.loadingTip+"|"+me.options.completeTip+")", "g");

    //创建JRoll
    me.jroll = new JRoll(wrap, jOptions);
    // me.jroll.on("scrollStart", function() {
    //   this.refresh();
    // });
    me.jroll.on("scrollEnd", function() {
      if (!me.lock) {
        //上滑
        if (this.y > -1*qSr(".jroll-infinite-tip").offsetHeight && me.options.limit) {
          me.direction = "-";

          //如果有上一页，则加载上一页
          if ((me.page - 3 >= 1) && (me.options.total > 3)) {
            me.page = me.page - 3;
            me.getData();
          }
        }
        //下滑
        if (this.y < this.maxScrollY + qSr(".jroll-infinite-tip").offsetHeight) {
          me.direction = "+";

          //如果有下一页，则加载下一页
          if ((me.page + 1 <= me.options.total) && (me.options.total > 2)) {
            me.page = me.page + 1;
            me.getData();
          }
        }
      }
    });
    
    //下拉刷新
    me.divPull = cDiv("div");
    me.divIcon = cDiv("span");
    me.divText = cDiv("span");
    
    me.divIcon.innerHTML = me.options.iconPull;
    me.divText.innerHTML = me.options.textPull;
    
    me.divPull.style.cssText = me.options.pullCss;
    me.divIcon.style.cssText = me.options.iconCss;
    me.divText.style.cssText = me.options.textCss;
    me.divIcon.style[tSD] = "200ms";
    
    me.divPull.appendChild(me.divIcon);
    me.divPull.appendChild(me.divText);
    me.jroll.wrapper.appendChild(me.divPull);
    
    me.jroll.on("scroll", function() {
      me.divPull.style[tSF] = "translateY("+this.y+"px)";
      if (!me.lock) {
        if (this.y >= me.divPull.offsetHeight) {
          if (!me.refresh) {
            me.refresh = true;
            me.divText.innerHTML = me.options.textRelease;
            me.divIcon.style[tSF] = "rotateZ(180deg)";
          }
        } else {
          if (me.refresh) {
            me.refresh = false;
            me.divText.innerHTML = me.options.textPull;
            me.divIcon.style[tSF] = "rotateZ(0deg)";
          }
        }
      }
    });
    
    me.jroll.scroller.addEventListener("touchend", function() {
      if (me.refresh && !me.lock) {
        me.jroll.options.momentum = false;
        me.jroll.options.bounce = false;
        me.jroll.scroller.style[tSD] = "200ms";
        me.jroll.scroller.style[tSF] = "translate(0px, " + me.divPull.offsetHeight + "px) translateZ(0) scale(" + me.jroll._zoom.scale + ")";
        me.divPull.style[tSD] = "200ms";
        me.divPull.style[tSF] = "translateY("+me.divPull.offsetHeight+"px)";
        setTimeout(function() {
          me.jroll.scroller.style[tSD] = "0ms";
          me.divPull.style[tSD] = "0ms";
        }, 200);
        me.setLoading();
        me.page = 1;
        me.getData();
      }
    }, false);

    //初始化
    me.init();
  }

  JRoll_Infinite.prototype = {
    init: function() {
      var me = this;
      me.getData();
    },
    setLoading: function() {
      var me = this;
      me.divText.innerHTML = me.options.textUpdate;
      me.divIcon.innerHTML = me.options.iconUpdate;
      me.divIcon.className = "jroll-infinite-loading";
    },
    getData: function() {
      var me = this;
      me.lock = true;
      me.setLoading();
      me.options.getData(me.page, me.callback.bind(me));
    },
    callback: function(data) {
      var me = this;
      var str, delChild, delHeight, id, html;

      me.lock = false;

      id = me.direction === "-" ? me.prefix+"page_"+(me.page - 2) : me.prefix+"page_"+me.page;
      html = "<section id='"+id+"'>";

      for (var i=0,l=data.length; i<l; i++) {
        html += me.parseTemplate(data[i]);
      }
      html += "</section>";
      
      me.divIcon.innerHTML = me.options.iconPull;
      me.divText.innerHTML = me.options.textPull;
      me.divIcon.className = "";
      me.divIcon.style[tSF] = "rotateZ(0deg)";

      if (me.refresh) {
        me.direction = "+";
        me.jroll.options.momentum = true;
        me.jroll.options.bounce = true;
        me.jroll.scroller.innerHTML = "";
        me.refresh = false;
        me.jroll.scrollTo(0, 0, 400);
        me.divPull.style[tSD] = "400ms";
        me.divPull.style[tSF] = "translateY(0px)";
        setTimeout(function() {
          me.divPull.style[tSD] = "0ms";
        }, 400);
      }

      if (me.direction === "-") {
        delChild = gId(me.prefix+"page_"+(me.page+1));
        delHeight = 1;
        me.jroll.scroller.removeChild(delChild);

        //不是第1页，顶部加上“正在加载”提示
        if (me.page - 2 !== 1) {
          str = me.options.loadingTip + html + me.jroll.scroller.innerHTML.replace(me.clearRegExp, "");
        } else {
          str =  html + me.jroll.scroller.innerHTML.replace(me.clearRegExp, "");
        }
      }

      if (me.direction === "+") {
        //大于第3页，顶部加上“正在加载”提示
        if (me.page - 3 > 0) {
          if (me.options.limit) { //使用增减模式
            delChild = gId(me.prefix+"page_"+(me.page-3));
            if (me.page === 4) {
              delHeight = delChild.offsetHeight - qSr(".jroll-infinite-tip").offsetHeight;
            } else {
              delHeight = delChild.offsetHeight;
            }
            me.jroll.scroller.removeChild(delChild);
            str = me.options.loadingTip + me.jroll.scroller.innerHTML.replace(me.clearRegExp, "") + html;
          } else {
            delHeight = 0;
            str = me.jroll.scroller.innerHTML.replace(me.clearRegExp, "") + html;
          }
        } else {
          str = me.jroll.scroller.innerHTML.replace(me.clearRegExp, "") + html;
        }
      }

      //不是最后一页，底部加上“正在加载”提示
      if (me.page !== me.options.total) {
        str += me.options.loadingTip;
      } else {
        str += me.options.completeTip;  //最后一页加“加载完成”提示
      }

      me.jroll.scroller.innerHTML = str;
      if (delHeight) {
        if (me.direction === "+") {
          me.jroll.scrollTo(0, me.jroll.y+delHeight);
        } else {
          if (me.page === 3) {
            delHeight = me.jroll.scroller.children[0].offsetHeight - qSr(".jroll-infinite-tip").offsetHeight;
          } else {
            delHeight = me.jroll.scroller.children[1].offsetHeight;
          }
          me.jroll.scrollTo(0, me.jroll.y - delHeight);
        }
      }
      me.jroll.refresh();

      //如果有第2页，则加载第2页
      // if ((me.page + 1 === 2) && (me.page + 1 <= me.options.total)) {
      //   me.lock = true;
      //   me.options.getData(++me.page, me.callback.bind(me));
      // }
    },
    parseTemplate: function(d) {
      var t = this.options.template;
      for (var i in d) {
        t = t.replace(new RegExp("{{"+i+"}}", "g"), d[i]);
      }
      return t;
    }
  };
  
  if (typeof module !== 'undefined' && module.exports && !normalImport) {
    module.exports = JRoll_Infinite;
  } else if (typeof define === 'function' && !normalImport) {
    define(function() {return JRoll_Infinite;});
  } else {
    window.JRoll_Infinite = JRoll_Infinite;
  }
  
})(window, document);
